﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VINETLIFE.DO;
using System.Data;
using VINETLIFE.BL;
using System.Web.UI.HtmlControls;

namespace VINETLIFE
{
    public partial class hotdeal : System.Web.UI.Page
    {
        public int idProduct = 0;
        public int iQty = 0;
        public string productTitle = "";
        cmsProductDO itemProductDO = new cmsProductDO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                if (!IsPostBack)
                {
                    FillForm();
                    h2web.InnerText = new sysConfigBL().Select(new sysConfigDO() { ConfigID = 1 }).ConfigValue;
                    MasterPage msPage = (MasterPage)this.Master;

                    UserControl ucHeader1 = (UserControl)msPage.FindControl("ucHeader1");
                    HtmlControl h1web = (HtmlControl)ucHeader1.FindControl("h1web");
                    h1web.Visible = false;

                    if (Session["shop"] == null)
                    {
                        Session["shop"] = new MyShopCart();
                    }
                    int number;
                    bool isNumber = int.TryParse(Request.QueryString["ID"], out number);
                    if (!isNumber) return;
                    idProduct = Convert.ToInt32(Request.QueryString["ID"]);
                    GetTags(idProduct);
                    // iQty = Convert.ToInt32(txtQty.Text);
                    LoadImageProduct(idProduct);
                    itemProductDO.ProductID = idProduct;
                    itemProductDO = new cmsProductBL().Select(itemProductDO);
                    productTitle = itemProductDO.ProductTitle;
                    LoadData();
                    // LoadDetail(idProduct);
                    rptProductPropertiesXDataSource(idProduct);
                    ShowDataListProduct();
                    ShowDataListPKDC();
                    FaceComment();
                    LoadSeo();
                    LoadAlbumProduct(idProduct);
                    ltrHuongDan.Text = new sysConfigBL().Select(new sysConfigDO() { ConfigID = 26 }).ConfigValue;
                    //Load color
                    LoadColor(idProduct);
                }
            }
            else
            {

            }
        }
        protected void FillForm()
        {
            if (Session["CustomerID"] != null)
            {
                int userID = int.Parse(Session["CustomerID"].ToString());
                cmsCustomerDO objUser = new cmsCustomerBL().Select(new cmsCustomerDO() { Id = userID });
                txtName.Text = objUser.FullName;
                txtEmail.Text = objUser.Email;
                txtPhone.Text = objUser.Phone;
                txtAddress.Text = objUser.Address;
            }
        }

        public string Tags = string.Empty;
        string GetTags(int id)
        {
            DataTable tb = new cmsProductBL().SelectByPK(id);
            DataRow dr = tb.Rows[0];
            Tags = dr["MetaTag"].ToString();
            return Tags;
        }
        void LoadColor(int poductID)
        {
            rptColor.DataSource = new ProductColorBL().GetByProduct(poductID);
            rptColor.DataBind();
        }

        void LoadSeo()
        {
            //MetaDes
            HtmlMeta metaKey = new HtmlMeta();
            metaKey.Name = "keywords";
            if (!string.IsNullOrEmpty(itemProductDO.MetaTag))
            {
                metaKey.Content = itemProductDO.MetaTag;
            }
            else
            {
                metaKey.Content = itemProductDO.Description;
            }
            Page.Header.Controls.Add(metaKey);

            //MetaKey
            HtmlMeta metaDesc = new HtmlMeta();
            metaDesc.Name = "description";
            if (!string.IsNullOrEmpty(itemProductDO.MetaDes))
            {
                metaDesc.Content = itemProductDO.MetaDes;
            }
            else
            {
                metaDesc.Content = itemProductDO.Description;
            }
            Page.Header.Controls.Add(metaDesc);
            if (!string.IsNullOrEmpty(itemProductDO.PageTitle))
            {
                Page.Title = itemProductDO.PageTitle;// +" | " + Ultility.WebTitle();
            }
            else
            {
                Page.Title = itemProductDO.ProductTitle;// +" | " + Ultility.WebTitle();
            }
        }

        void FaceComment()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                string cururl = "http://" + Request.Url.Host + Request.Url.AbsolutePath;
                //      cmfb.Attributes.Add("data-href", cururl);
            }
        }
        protected void rpListProduct_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
        }
        protected void btnCart_Click(object sender, EventArgs e)
        {
            //  AddItem();
            //    button.Attributes.Add("onlick","updateCart(" + Convert.ToInt32(Request.QueryString["ID"]) + ","  + txtQty.Text + "); return false;");
        }
        cmsProductBL data = new cmsProductBL();

        public string imageProduct = "images.jpg";
        public string Thumbnail = "images.jpg";
        void LoadData()
        {
            int idParent = itemProductDO.ProductCategoryID;
            cmsProductCategoryDO itemParent = new cmsProductCategoryDO();
            cmsProductCategoryBL itemParentBL = new cmsProductCategoryBL();
            itemParent.ProductCategoryID = idParent;
            itemParent = itemParentBL.Select(itemParent);

            lblTitleParent.Text = itemParent.ProductCategoryTitle;
            lblTitle.Text = itemProductDO.ProductTitle;
            ltProductTitle.Text = itemProductDO.ProductTitle;
            lbId.Text = itemProductDO.ProductCode;
            ltrDesc.Text = itemProductDO.Description;
            lblWarranty.Text = itemProductDO.Warranty;
            ltrDetail.Text = itemProductDO.DetailDescription;
            lblOldPrice.Text = string.Format("{0:0,0}", itemProductDO.Price);
            if (itemProductDO.Active)
            {
                lblTrangThai.Text = "Còn hàng";
                lblTrangThai.Attributes.Add("class", "deal-avaliable");
            }
            else
            {
                lblTrangThai.Text = "Hết hàng";
                lblTrangThai.Attributes.Add("class", "deal-unavaliable");
            }
            DateTime timeCountDown = itemProductDO.PromotionEndDate;
            lblCountDown.Text = "<script type='text/javascript'>$(function () {var austDay = new Date();austDay = new Date(" + timeCountDown.Year + "," + (timeCountDown.Month - 1) + "," + timeCountDown.Day + "," + timeCountDown.Hour + "," + timeCountDown.Minute + "," + timeCountDown.Second + ");$('#defaultCountdownHotdeal').countdown({ until: austDay, format: 'yowDHMS'});$('#year').text(austDay.getFullYear());});</script>";
            if (itemProductDO.ProductImage != null)
                imageProduct = itemProductDO.ProductImage;
            if (!string.IsNullOrEmpty(itemProductDO.Thumbnail))
                Thumbnail = itemProductDO.Thumbnail;
            else
                Thumbnail = imageProduct;
            int Originid = itemProductDO.OriginID;
            cmsOriginDO itemDO = new cmsOriginDO();
            cmsOriginBL itemBL = new cmsOriginBL();
            itemDO.OriginID = Originid;
            itemDO = itemBL.Select(itemDO);
            lbXuatxu.Text = "<a href='/nha-san-xuat/" + Ultility.Change_AV(itemDO.Origin) + "-" + itemDO.OriginID + "' title = '" + itemDO.Origin + "'>" + itemDO.Origin + "</a>";
            string status = string.Empty;
            lbStatus.Text = (itemProductDO.Active) == true ? "Còn hàng" : "Hết hàng";

            if (itemProductDO.IsPromotion)
            {
                if (itemProductDO.SalePrice > 0)
                {
                    lbCost.Text = string.Format("{0:0,0 VNĐ}", itemProductDO.SalePrice);
                }
                else
                {
                    lbCost.Text = "Liên Hệ";
                }
            }
            else
            {
                if (itemProductDO.Price > 0)
                {
                    lbCost.Text = string.Format("{0:0,0 VNĐ}", itemProductDO.Price);
                }
                else
                    lbCost.Text = "Liên Hệ";
            }

            Label lbAbout = new Label();
            if (!string.IsNullOrEmpty(itemProductDO.DetailDescription))
                lbAbout.Text = itemProductDO.DetailDescription.ToString();
            else lbAbout.Text = "Đang cập nhật...";
            //    infoAbout.Controls.Add(lbAbout);
        }

        cmsProductPropertyDO itemProductPropertyDO = new cmsProductPropertyDO();
        cmsPropertiesDO itemPropertyDO = new cmsPropertiesDO();
        public string name = string.Empty;
        public string nameDetail = string.Empty;
        void LoadDetail(int productID)
        {
            //rptProductProperties.DataSource = new cmsProductPropertyBL().SelectByProductID(productID);
            //rptProductProperties.DataBind();
        }

        protected void rptListProperties_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
        {

            Label ltID = (Label)e.Item.FindControl("lblPropertyID");
            Label ltName = (Label)e.Item.FindControl("lblPropertyName");
            Label ltValue = (Label)e.Item.FindControl("lblValue");
            if (ltValue.Text.Equals("N/A") || ltValue.Text.Equals(""))
            {
                ltName.Visible = false;
                ltValue.Visible = false;
                ltID.Visible = false;
            }
            //if (ltValue.Text == null)
            //    ltValue.Text = "N/A";
            //TextBox txtValue1 = (TextBox)e.Item.FindControl("txtValue");
            cmsPropertiesDO itemDO = new cmsPropertiesBL().Select(new cmsPropertiesDO() { PropertyID = int.Parse(ltID.Text) });
            if (itemDO.ParentID == 0)
            {
                // ltValue.Text = "";
                ltName.CssClass = "pro-left1";

            }
            else
            {
                ltName.CssClass = "pro-left";
            }
        }


        void LoadAlbumProduct(int productID)
        {
            DataTable dtAlbum = new MediaBL().GetTopProductId(productID, 0);
            rptMainImage.DataSource = dtAlbum;
            rptThumbnail.DataSource = dtAlbum;

            rptMainImage.DataBind();
            rptThumbnail.DataBind();
        }
        void LoadImageProduct(int productID)
        {
            MediaBL itemBL = new MediaBL();
            DataTable tb = itemBL.GetTopProductId(productID, 4);
            listImage.DataSource = tb;
            listImage.DataBind();
        }
        void ShowDataListProduct()
        {

        }


        void ShowDataListPKDC()
        {
        }

        protected string FriendlyUrl(string s)
        {
            return Ultility.Change_AV(s);
        }
        //Property
        protected void rptProductPropertiesXDataSource(int productID)
        {
            rptProductPropertiesX.DataSource = new cmsProductPropertyBL().SelectByProductAndParent(productID, 0);
            rptProductPropertiesX.DataBind();
        }
        protected void rptProductPropertiesX_DataBound(object sender, RepeaterItemEventArgs e)
        {
            int productID = int.Parse(Request.QueryString["ID"]);
            DataRowView drv = (DataRowView)e.Item.DataItem;
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                int parentID = int.Parse(drv["PropertyID"].ToString());
                Repeater rptChildProperty = (Repeater)e.Item.FindControl("rptChildProperty");
                rptChildProperty.DataSource = new cmsProductPropertyBL().SelectByProductAndParent(productID, parentID);
                rptChildProperty.DataBind();
            }
        }
        protected void rptChildProperty_DataBound(object sender, RepeaterItemEventArgs e)
        {

            DataRowView drv = (DataRowView)e.Item.DataItem;

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Panel pnlChild = (Panel)e.Item.FindControl("pnlChild");
                if (string.IsNullOrEmpty(drv["Value"].ToString()))
                {
                    pnlChild.Visible = false;
                }
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {

        }

        protected void btnCartHotdeal_Click(object sender, EventArgs e)
        {
            try
            {
                SendMail(txtName.Text.Trim(), txtAddress.Text.Trim(), txtPhone.Text.Trim(), txtEmail.Text.Trim(), txtDateOfFunction.Text.Trim());
                Ultility.Alert("Gửi đơn hàng thành công","/");
            }
            catch 
            {
            }
        }
        string strFromMail = "no-reply@ses.vn";
        string strFromPass = "@@ses123";
        void SendMail(string name, string address, string phone, string email, string dateOf)
        {
            cmsProductDO myShop = new cmsProductBL().Select(new cmsProductDO() { ProductID = int.Parse(Request.QueryString["ID"]) });
            DateTime now = DateTime.Now;
            string date = now.Day + " - " + now.Month + " - " + now.Year;

            //MyShopCart myShop = (MyShopCart)Session["shop"];
            string totalCost = String.Format("{0:0,0}", myShop.SalePrice);

            string content = "<div style='margin-top:10px'>";
            content += "<fieldset>";
            content += "<legend>Thông tin đặt hàng</legend>";
            content += " <table width='100%' border='1' cellpadding='3' cellspacing='0' style='border-collapse:collapse'>";
            content += "<tbody><tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Thông tin khách hàng </td></tr>";
            content += "<tr><td style='width:150px'>Họ tên : </td><td>" + name + "</td></tr>";
            content += "<tr><td>Địa chỉ : </td><td>" + address + "</td></tr>";
            content += "<tr><td>Điện thoại : </td><td>" + phone + "</td></tr> ";
            content += "<tr><td>Email : </td><td>" + email + "</td></tr>";
            content += "<tr><td>Ngày nhận hàng : </td><td>" + dateOf + "</td></tr>";
            content += "<tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Thông tin sản phẩm đặt hàng </td></tr>";
            content += "<tr><td style='width:150px'>Sản phẩm</td><td>" + myShop.ProductTitle + "<tr><td>Mã : </td><td>" + myShop.ProductCode + "</td></tr><tr><td> Số lượng :</td><td> 1</td></tr><tr><td>Giá gốc</td><td>"+string.Format("{0:0,0}",myShop.Price) +" VNĐ</td></tr><tr><td> Giá hotdeal:</td><td> " + String.Format("{0:0,0}", myShop.SalePrice) + " VNĐ</td></tr>";
            content += "<tr bgcolor='#999999' style='color:#FFF'><td colspan='2'>Tổng giá trị : " + totalCost + " VNĐ</td></tr>";
            content += "</table>";
            content += "<p>Ngày gửi : " + date + "</p></fieldset></div>";
            string AdminEmail = new sysConfigBL().Select(new sysConfigDO() { ConfigID = 7 }).ConfigValue;
            Myfunction.SendMail(strFromMail, strFromPass, "Đơn đặt hàng Hotdeal của khách hàng: " + name, AdminEmail, "Đơn đặt hàng ngày " + now.ToString("dd/MM/yyyy HH:mm t"), content);
        }
    }
}